package com.example.springboot.controller.web;

import cn.hutool.core.io.FileUtil;
import com.example.springboot.common.AuthAccess;
import com.example.springboot.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * 功能
 * 作者：八滴水
 * 日期： 2024/12/11 15:15
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${ip:localhost}")
    String ip;

    @Value("{server.port}")
    String port;

    private  static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";
    @AuthAccess
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String mainName = FileUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);
        File parentFile = new File(ROOT_PATH);
        if(!parentFile.exists()){
            parentFile.getParentFile().mkdirs();
        }
        if(parentFile.exists ()){
            originalFilename =System.currentTimeMillis() + "_" + mainName + "." + extName;
        }
        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        file.transferTo(saveFile);
        String url = "http://" + ip +":"+ port + "/file/download/" + originalFilename;
        return Result.success(url);

    }
    @AuthAccess
    @GetMapping("/download/{fileName}")
    public void download(String fileName, HttpServletResponse response) throws IOException
    {
        String filePath = ROOT_PATH + File.separator + fileName;
        if(FileUtil.exist(filePath)){
            return;

        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();

    }
}
